<?php
	// TODO: enforce login policy
	// TODO: check for if user is admin when admin functionality is asked for.
	require_once("globals.php");
	require_once('/ticket/ticket_functions.php');
	
	if($_SERVER['REQUEST_METHOD'] == 'POST'):
		handlePost();
	elseif ($_SERVER['REQUEST_METHOD'] == 'GET'):
		
	endif;
	
	function handlePost()
	{
		if(isset($_POST['command'])):
			handleCommand();
		else:
		endif;
	}
	
	function handleCommand()
	{
		$command = $_POST['command'];
		switch($command)
		{
			case "isUserAdmin":
				commandIsUserAdmin();
				break;
			case "whoIsLoggedIn":
				commandWhoIsLoggedIn();
				break;
			case "logoutCurrentUser":
				commandLogoutCurrentUser();
				break;
			case "getAllTickets":
				getAllTickets();
				break;
			case "getUserEmail":
				getUserEmail();
				break;
			case "submitNewTicket":
				submitNewTicket();
				break;
			case "closeTicket";
				close_ticket();
				break;
			case "reopenTicket";
				reopen_ticket();
				break;
			case "assignSelfToTicket":
				assign_SelfToTicket();
				break;
			case "removeSelfFromTicket":
				remove_SelfFromTicket();
				break;
			case "deleteTicket":
				delete_ticket();
				break;
			case "sendEmail":
				send_email();
			case "updateUserPassword":
				update_UserPassword();
				break;
			default:
				echo "Error: did not hit any of case statements when handling post in globa_ajax.php";
				break;				
		}
	}
	
	function update_UserPassword()
	{
		require('\private\mysqli_connect.php');
		$newPassword = $_POST['newPassword'];
		$userID = $_SESSION['userID'];
		$query = 	"update users set password=SHA1('" . $newPassword . "')
					where user_id = $userID";
		$result = $db->query($query);
		
		if($result):
			// echo "success<br/>";
			//concatElementByID("message", "success");
			echo "newPassword: $newPassword     success";
			return true;
		else:
			// concatElementByID($elementID, "failure: " . $db->error);
			// echo $db->error . "<br/>";
			echo "error";
			return false;
		endif;
	}
	
	function send_email()
	{
		$sender = str_replace('-', '+', sanitizeString($_POST['sender']));
		$receiver = str_replace('-', '+', sanitizeString($_POST['receiver']));
		$subject = sanitizeStringKeepSpaces($_POST['subject']);
		$message = sanitizeStringKeepSpaces($_POST['message']);
		require_once('/email/email.php');
		sendEmail($sender, $receiver, $subject, $message);
		// echo "'$sender'  '$receiver'   $subject    $message";
		echo "success";
	}
	
	function delete_ticket()
	{
		require_once('/ticket/ticket_functions.php');
		if(!isset($_POST['ticketID'])):
			echo "ticketID was not set for closeTicket command";
			return false;
		endif;
		if(deleteTicket($_POST['ticketID'])):
			echo "success";
			return true;
		else:
			echo "error";
			return false;
		endif;
	}
	
	function remove_SelfFromTicket()
	{
		require_once('/ticket/ticket_functions.php');
		if(!isset($_POST['ticketID'])):
			echo "ticketID was not set for closeTicket command";
			return false;
		endif;
		if(removeSelfFromTicket($_POST['ticketID'])):
			echo "success";
			return true;
		else:
			echo "error";
			return false;
		endif;
	}
	
	function assign_SelfToTicket()
	{
		require_once('/ticket/ticket_functions.php');
		if(!isset($_POST['ticketID'])):
			echo "ticketID was not set for closeTicket command";
			return false;
		endif;
		if(assignSelfToTicket($_POST['ticketID'])):
			echo "success";
			return true;
		else:
			echo "error";
			return false;
		endif;
	}
	
	function reopen_ticket()
	{
		require_once('/ticket/ticket_functions.php');
		if(!isset($_POST['ticketID'])):
			echo "ticketID was not set for closeTicket command";
			return false;
		endif;
		if(reopenTicket($_POST['ticketID'])):
			echo "success";
			return true;
		else:
			echo "error";
			return false;
		endif;
	}
	
	function close_ticket()
	{
		require_once('/ticket/ticket_functions.php');
		if(!isset($_POST['ticketID'])):
			echo "ticketID was not set for closeTicket command";
			return false;
		endif;
		if(closeTicket($_POST['ticketID'])):
			echo "success";
			return true;
		else:
			echo "error";
			return false;
		endif;
	}
	
	function submitNewTicket()
	{
		$firstName = sanitizeString($_POST['senderFirstName']);
		$lastName = sanitizeString($_POST['senderLastName']);
		$email = sanitizeString($_POST['senderEmail']); // a little redundant
		$email = str_replace('-', '+', $email);
		// TODO: remove hard code
		// $email = "cmb155+bob@pitt.edu";
		$subject = sanitizeStringKeepSpaces($_POST['subject']);
		$description = sanitizeStringKeepSpaces($_POST['description']);
		// echo  "submitNewTicket() in globa_ajax ". $firstName . ":" . $lastName . ":" . $email . ":" . $subject . ": $description";
		if($firstName && $lastName && $email && $subject && $description):
			require("/ticket/create_ticket.php");
			if(createNewTicket($firstName, $lastName, $email, $subject, $description)):
				echo "success";
				return true;
			else:
				echo "error";
				return false;
			endif;
		else:
			echo "error";
			return false;
		endif;
	}
	
	function getUserEmail()
	{
		$username = $_SESSION['username'];
		require("private\mysqli_connect.php");
		$result = $db->query("select email from users where username ='" . $username . "'");
		$rows = $result->num_rows;
		if($rows > 0):
			$row = $result->fetch_array();
			$email = $row['email'];
			echo "$email";
			return true;
		else:
			echo "error";
			return false;
		endif;	
	}
	
	function getAllTickets()
	{
		if(!isset($_POST['buttonMode'])):
			echo "forgot to set button mode";
			return false;
		endif;
		$buttonMode = $_POST['buttonMode'];
		if(!userIsAdminInSession() && strcmp($buttonMode, "ViewUserTickets") != 0):
			echo "not admin";
			return false;
		endif;
		require('\private\mysqli_connect.php');
		$query = createTicketQuery($buttonMode);
		$result = $db->query($query);
		if(!$result):
			echo "No tickets found";
			return false;
		endif;
		$rows = $result->num_rows;
		$tickets = "";
		for($i = 0; $i < $rows; $i++):
			$row = $result->fetch_array();
			$current_username = $row['username'];
			$status = $row['ticket_is_open'] ? "open" : "closed";
			$tickets .= $row['ticket_id'] . ',' . $row['received'] . ',' . $row['sender_firstname'] . 
					' ' . $row['sender_lastname'] . ',' . $row['sender_email'] . ',' . $row['subject'] 
					. ',' . $row['username'] . ',' . $status . "," . $row['description'];
			if(($i + 1) < $rows):
				$tickets .= "|";
			endif;
		endfor;
		echo $tickets;		
	}
	
	function createTicketQuery($buttonMode)
	{// TODO: finish queries
		$username = $_SESSION['username'];
		$userIsAdmin = $_SESSION['userIsAdmin'];
		$columns =  " ticket_id, received, sender_firstname, sender_lastname, sender_email, 
					subject, username, ticket_is_open, description ";
		switch($buttonMode)
		{
			case "ViewAllTickets":
				$query = 	"select " . $columns . " from tickets left join users on
					tickets.user_id = users.user_id";
				return $query;
			case "ViewAdminTickets":
				$query = 	"select " . $columns . " from tickets join users on tickets.user_id = users.user_id
							where users.username = '" . $username .  "'";
				return $query;
			case "ViewUserTickets":
				$query = 	"select " . $columns . " from tickets left join users on users.user_id = tickets.user_id
							where tickets.sender_email = (select email from users where username = '" . $username . "')";
				return $query;
			case "ViewUnassignedTickets":
				$query = 	"select " . $columns . " from tickets left join users on tickets.user_id = users.user_id
							where tickets.user_id < 1 or tickets.user_id is null";
				return $query;
			case "ViewOpenTickets":
				$query = 	"select " . $columns . " from tickets left join users on tickets.user_id = users.user_id 
							where tickets.ticket_is_open = true";
				return $query;
			case "findSubmitterTickets":
				$ticketID = $_POST['ticketID'];
				$row = getTicketInfo($ticketID);				
				$email = $row['sender_email'];
				$query = 	"select " . $columns . " from tickets left join users on tickets.user_id = 
							users.user_id where sender_email = '" . $email ."'";
				// echo "findSubmitterTickets: #$ticketID  email: $email  query: $query";
				return $query;
			case "findSimilarTickets":				
				$query = 	"select " . $columns . " from tickets left join users on 
							tickets.user_id = users.user_id";
				$ticketID = $_POST['ticketID'];
				$row = getTicketInfo($ticketID);				
				$subject = $row['subject'];
				$words = explode(' ', $subject);			
				foreach($words as $key => $word):
					if($key == 0):
						$query .= " where subject like '%" . $word . "%'";
					elseif($key > 0):
						$query .= " or subject like '%" . $word . "%'";
					endif;
				endforeach;
				// echo "findSubmitterTickets: #$ticketID  email: $email  query: $query";
				return $query;
			default:
				return "";
				break;
		}
		
	}
	
	function commandLogoutCurrentUser()
	{
		destroySession();
	}
	
	function commandIsUserAdmin()
	{
		if(!isset($_SESSION['username'])):
			echo "false";
			return;
		endif;
		$username = $_SESSION['username'];
		if(userIsAdmin($username)):
			echo "true";			
		else:
			echo "false";
		endif;
	}
	
	function commandWhoIsLoggedIn()
	{
		if(!isset($_SESSION['username'])):
			echo "";
			return;
		endif;
		$username = sanitizeString($_SESSION['username']);
		echo $username;
	}
	
	
?>